package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"jd-mall/models/cache"
	"jd-mall/models/mysql"
	"strconv"
	"time"

	"jd-mall/jd_srv/internal/svc"
	"jd-mall/jd_srv/jd_srv"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddShoppingCartLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddShoppingCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddShoppingCartLogic {
	return &AddShoppingCartLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *AddShoppingCartLogic) AddShoppingCart(in *jd_srv.AddShoppingCartRequest) (*jd_srv.AddShoppingCartResponse, error) {
	// todo: add your logic here and delete this line
	var shop mysql.Shops
	tx := mysql.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()

	if err := tx.Error; err != nil {
		return nil, fmt.Errorf(err.Error())
	}

	if err := tx.Where("id = ?", in.ShopId).Find(&shop).Error; err != nil {
		tx.Rollback()
		return nil, fmt.Errorf(err.Error())
	}
	if shop.ShopInventory <= 0 {
		return nil, fmt.Errorf("库存不足，无法添加")
	}
	// 检查是否存在
	get := cache.RDB.Get(l.ctx, "shopId:"+strconv.Itoa(int(in.ShopId))).Val()
	if get != "" {
		// 存在则数量+1
		cache.RDB.Incr(l.ctx, "ShopId:"+strconv.Itoa(int(in.ShopId))+"_Count")
		cache.RDB.Expire(l.ctx, "ShopId:"+strconv.Itoa(int(in.ShopId))+"_Count", time.Hour*24)
	} else {
		// 不存在则添加
		marshal, _ := json.Marshal(&shop)
		cache.RDB.Set(l.ctx, "shopId:"+strconv.Itoa(int(in.ShopId)), marshal, time.Hour*24)
	}
	return &jd_srv.AddShoppingCartResponse{}, nil
}
